package com.netty.esc.service.action;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netty.esc.entity.send.ProtocolACKDTO;
import com.netty.esc.service.isolate.CommonFriendService;
import com.netty.esc.service.isolate.UserBroadcast;
import com.netty.esc.common.enums.WSProtocolTypeEM;
import com.netty.esc.entity.model.PersonTalkDTO;
import com.netty.esc.config.websocket.ChannelGroups;
import com.netty.esc.config.websocket.WebSocketManager;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author: ext.zhaoyang17
 * @date: 2022.11.04
 * 用户行为类
 */
@Service
@Slf4j
public class UserAction extends BaseAction{

    @Resource
    UserBroadcast userBroadcast;
    @Resource
    CommonFriendService commonFriendService;

    @Resource
    MongoTemplate mongoTemplate;

    /**
     * 用户上线
     * @param ctx
     * @param jsonObject
     */
//    @ActionType(WSProtocolTypeEM.ONLINE)



    /**
     * 私聊
     */
    @ActionType(WSProtocolTypeEM.PERSON_MSG)
    public void personTalk(ChannelHandlerContext ctx, JSONObject jsonObject){

        ProtocolACKDTO protocolACKDTO = new ProtocolACKDTO(jsonObject);
        try {
            PersonTalkDTO personTalkDTO = jsonObjectToModel(jsonObject, PersonTalkDTO.class);
            Long userId = ChannelGroups.channelToRobot.get(ctx.channel().id());
            personTalkDTO.setUserId(userId);
            Long receiverId = personTalkDTO.getReceiverId();
            //初始化消息状态 0 状态正常 1 撤回
            personTalkDTO.setChatStatus(0);
            personTalkDTO.setProtocolType(WSProtocolTypeEM.PERSON_MSG.code());
            personTalkDTO.setCreateTime(new Date());
//            personTalkDTO.setMessageTypeEnum();
            Channel channelByUerId = ChannelGroups.getChannelByUerId(receiverId);
            mongoTemplate.save(personTalkDTO);
            if (channelByUerId!=null){
                WebSocketManager.sendTextMessage(channelByUerId, personTalkDTO);
                return;
            }
            //处理离线消息
            commonFriendService.offOlineMessageSave(personTalkDTO.getReceiverId(), personTalkDTO.getUserId(), personTalkDTO.getCreateTime());
        }catch (Exception ex) {
            log.error("UserAction.personTalk exception is {}", JSON.toJSONString(ex));
        }
        WebSocketManager.sendTextMessage(ctx,protocolACKDTO);
    }

    /**
     * 群聊
     */
    @ActionType(WSProtocolTypeEM.PEOPLE_MSG)
    public void peopleTalk(ChannelHandlerContext ctx, JSONObject jsonObject){
        ProtocolACKDTO protocolACKDTO = new ProtocolACKDTO(jsonObject);
    }


}
